$(document).ready(function() {
    var cdnUrl = "";
    var default_count = {totalfee:0,discountfee:0,originalfee:0,modifyfee:0,discount:0,carddiscount:0,vipdiscount:0};
    var data_type = 'goods';
    var currentkey = sessionStorage.getItem('currentkey');
    if (currentkey) {
        var current_key = JSON.parse(currentkey);
        data_type = current_key['datatype'];
    }

    $(".active-btn-item").removeClass('active-btn-item');
    $(".btn-item[data-datatype='"+data_type+"']").addClass('active-btn-item');
    //初始化数据
    initdata(data_type);

    //预览图片
    $(document).on("click", ".img-review", function (event) {
        event.stopPropagation();
        $('#img-responsive').attr('src', $(this).prop('src'));
        $('#imgModal').modal('show');
    });

    //新增客户
    $(document).on("click", ".add-customer", function () {
        $('#addUserModal').modal('show');
    });

    //新增客户--保存客户信息
    $(document).on("click", ".btn-save-customer", function () {
        var mobile = $(".mobile-text").val();
        var nickname = $(".nickname-text").val();
        var gender = $(".radio-gender:checked").val();

        //验证手机号
        var phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(mobile)) {
            layer.open({
                type: 1, 
                title:'提示信息',
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">手机号格式错误，请确认后重试</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    // 点击确定按钮后的回调函数
                    // index是弹窗的索引，layero是弹窗的DOM对象
                    layer.close(index); // 关闭弹窗
                }
            });
            return false;
        }

        $.ajax({
            type: 'POST',
            url: 'cashdesk/index/adduser',
            dataType: "json",
            data: {
                mobile:mobile,
                nickname:nickname,
                gender:gender
            },
            success: function (ret) {
                if (ret.code != 1) {
                    layer.open({
                        title:'提示信息',
                        type: 1, 
                        area: ['280px', '180px'],
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                            $(".mobile-text").val('').focus();
                        }
                    });
                    return false;
                }else{
                    $(".mobile-text").val('');
                    $(".nickname-text").val('');
                    $(".radio-gender:checked").val(1);
                    $('#addUserModal').modal('hide');
                }
            },
            error: function (ret) {
                layer.open({
                    title:'提示信息',
                    type: 1, 
                    area: ['280px', '180px'],
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        // 点击确定按钮后的回调函数
                        // index是弹窗的索引，layero是弹窗的DOM对象
                        layer.close(index); // 关闭弹窗
                    }
                });
                $(".mobile-text").val('');
                $(".nickname-text").val('');
                $(".radio-gender:checked").val(1);
                $('#addUserModal').modal('hide');
            }
        });
        return false;
    });

    //选择客户
    $(document).on("click", ".label-choose-user", function () {
        $('#chooseUserModal').modal('show').on('shown.bs.modal', function () {
            setTimeout(() => {
                $('#choose-mobile').trigger('focus');
            }, 50);
        });
    });

    //选择客户--筛选客户信息
    $(document).on("click", ".btn-search", function () {
        var mobile = $(".choose-mobile-text").val();
        $.ajax({
            type: 'POST',
            url: 'cashdesk/index/searchuser',
            dataType: "json",
            data: {
                mobile:mobile,
            },
            success: function (ret) {
                if (ret.code != 1) {
                    layer.open({
                        type: 1,
                        title:'提示信息',
                        area: ['280px', '180px'],
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                            $(".choose-mobile-text").val('').focus();
                        }
                    });
                    return false;
                }else{
                    var list = ret.data;
                    if(list.length > 0){
                        var user_list = '<ul class="item-ul">';
                        $.each(list,function(index,value){
                            user_list += '<li class="item-li">';
                            user_list += '<h5 class="item-title">'+value.nickname+'('+value.username+')</h5>';
                            user_list += '<input type="hidden" value="'+value.id+'" class="user_id">';

                            user_list += '<input type="hidden" value="'+value.money+'" class="user_money">';
                            user_list += '<input type="hidden" value="'+value.score+'" class="user_score">';
                            user_list += '<input type="hidden" value="'+value.group_id+'" class="user_level">';
                            user_list += '<input type="hidden" value="'+value.group.discount+'" class="level_discount">';

                            user_list += '<input type="hidden" value="'+value.avatar+'" class="user_avatar">';
                            user_list += '<span class="item-mobile">手机号：<span class="user_mobile">'+value.mobile+'</span></span>';
                            user_list += '<span class="item-group">等级：<span class="user_groupname">'+value.group.name+'</span></span>';
                            user_list += '<span class="item-shop">所属店铺：'+value.shop.shopname+'</span>';
                            user_list += '</li>';
                        });
                        user_list += '</ul>';
                        $('.user-list').html(user_list);
                    }
                }
            },
            error: function (ret) {
                layer.open({
                    type: 1, 
                    area: ['280px', '180px'],
                    title:'提示信息',
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        // 点击确定按钮后的回调函数
                        // index是弹窗的索引，layero是弹窗的DOM对象
                        layer.close(index); // 关闭弹窗
                    }
                });
                $(".choose-mobile-text").val('');
                $('#chooseUserModal').modal('hide');
            }
        });
        return false;
    });

    
    const input = document.getElementById('choose-mobile');
    input.addEventListener('keydown', function(event) {
      if (event.key === 'Enter' || event.keyCode === 13) {
        event.preventDefault(); // 阻止默认行为（如表单自动提交）
        // 执行自定义提交逻辑
        document.getElementById('btn-search').click();
      }
    });

    //选择会员
    $(document).on("click", ".item-li", function () {
        var datatype = $(".active-btn-item").data("datatype");
        var user_id = $(this).find('.user_id').val();
        var user_avatar = $(this).find('.user_avatar').val();
        var user_nickname = $(this).find('.item-title').text();
        var user_mobile = $(this).find('.user_mobile').text();
        var user_groupname = $(this).find('.user_groupname').text();
        var user_money = $(this).find('.user_money').val();
        var user_score = $(this).find('.user_score').val();
        var user_level = $(this).find('.user_level').val();
        var level_discount = $(this).find('.level_discount').val();
        if(user_id != 0){
            var user_info = {
                id:user_id,
                nickname:user_nickname,
                mobile:user_mobile,
                groupname:user_groupname,
                avatar:user_avatar,
                money:user_money,
                score:user_score,
                level:user_level,
                level_discount:level_discount,
            }; 
            //保存客户信息到session
            var serializedArray = JSON.stringify(user_info);
            sessionStorage.setItem('customer', serializedArray);

            //另存用户信息
            var serializedArray = JSON.stringify(user_info);
            sessionStorage.setItem('user_'+user_info.id, serializedArray);

            var show_user_info_html = '<div class="col-md-2">';
                if (user_avatar != '') {
                    show_user_info_html += '<img class="goods-img img-review" src="'+user_avatar+'" alt=""></div>';
                }else{
                    show_user_info_html += '<img class="goods-img img-review" src="/assets/addons/wanlshop/img/common/mine_def_touxiang_3x.png" alt=""></div>';
                }
                
                show_user_info_html += '<div class="col-md-6">';
                show_user_info_html += '<div class="row"><label>'+user_nickname+'  '+user_groupname+'</label></div>';
                show_user_info_html += '<div class="row"><label>'+user_mobile+'</label></div></div>';
                show_user_info_html += '<div class="col-md-4 re-choose-user">重新选择</div>';
            $('.label-choose-user').addClass('label-choosed-user').html(show_user_info_html);
            //初始化数据
            initdata(datatype);
        }
        layer.close(); // 关闭弹窗
        $(".user-list").html("");
        $(".choose-mobile-text").val('');
        $('#chooseUserModal').modal('hide');
    });

    $(document).on("click", ".radio-server", function () {
        curboj.prop("checked", !curboj.prop('checked'));
    });

    $(document).on("click", ".server-item", function () {
        // 取消同组其他 radio 的选中
        // $(this).siblings(".server-item").find(".radio-server").prop("checked", false);
  
        // 选中当前项的 radio
        let curboj = $(this).find(".radio-server");
        curboj.prop("checked", !curboj.prop('checked'));
  
        // 添加视觉反馈（如高亮背景）
        // $(this).addClass("active").siblings().removeClass("active");
    });

    //选择服务人员
    $(document).on("click", ".card-attendant", function () {
        var specid = $(this).data('specid');
        $.ajax({
            type: 'POST',
            url: 'cashdesk/index/getstafflist',
            dataType: "json",
            data: {},
            success: function (ret) {
                if (ret.code != 1) {
                    layer.open({
                        type: 1,
                        title:'提示信息',
                        area: ['280px', '180px'],
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">暂无可用员工，请先到后台添加可用员工！</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                        }
                    });
                    return false;
                }else{
                    var staff_list = ret.data;
                    var staff_html = '';
                    if(staff_list.length != 0){
                        for (var staff in staff_list) {
                            staff_html += '<div class="server-item" data-id="'+staff_list[staff]['id']+'" data-specid="'+specid+'"><div class="col-xs-10">';
                            if (!staff_list[staff]['portraitimage']) {
                                staff_html += '<img src="/assets/img/avatar.png" class="staff_img" alt="">';
                            }else{
                                staff_html += '<img src="'+staff_list[staff]['portraitimage']+'" class="staff_img" alt="">';
                            }

                            
                            
                            staff_html += '<span class="staff_name">'+staff_list[staff]['name']+'('+staff_list[staff]['rank_name']+')</span>';
                            staff_html += '</div><div class="col-xs-2 staff_radio">';
                            staff_html += '<input class="radio-server" name="server_checkbox" type="checkbox" value="'+staff_list[staff]['id']+'"><label class="server-label"></label></div></div>';   
                        }
                    }

                    if(staff_html != ''){
                        $(".server-item-list").html(staff_html);
                        staff_html = '';
                        $('#chooseServerModal').modal('show');
                    }
                }
            },
            error: function (ret) {
                layer.open({
                    type: 1, 
                    area: ['280px', '180px'],
                    title:'提示信息',
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        // 点击确定按钮后的回调函数
                        // index是弹窗的索引，layero是弹窗的DOM对象
                        layer.close(index); // 关闭弹窗
                    }
                });
            }
        });
        return false;
    });

    //选择服务人员--保存客户信息
    $(document).on("click", ".btn-choose-server", function () {
        var datatype = $(".active-btn-item").data("datatype");
        var radioobj = $('input[name="server_checkbox"]:checked');
        var serve_html = "";
        var staffnames = '';
        var serveids = [];
        var specid = 0;
        if (radioobj.length > 0) {
            radioobj.each(function(index, element) {
                var ele_val = element.value;
                var par_element = $('.server-item[data-id='+ele_val+']')
                specid = par_element.data('specid');//商品属性id
                var serveid = ele_val;
                serveids[serveids.length] = serveid;
                var staffname = par_element.find('.staff_name').text();
                staffnames += '<'+staffname+'>';
            });
            var _serveids = serveids.join(',');
            serve_html += '<span style="margin-left: 10px;">'+staffnames+'<img src="'+cdnUrl+'/assets/cashdesk/img/right-icon.svg" class="right-icon" /> </span>';
            $('.card-attendant[data-specid="'+specid+'"]').attr('data-serveid',_serveids);
            $('.card-attendant[data-specid="'+specid+'"]').html(serve_html);
            //将服务人员添加到购物车对象中
            var customerinfo =  sessionStorage.getItem('customer');
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;

            var objkey = 'goodsorder_'+user_id;
            if (datatype == "cards") {
                objkey = 'cardsorder_'+user_id;
            }

            var ordersList = sessionStorage.getItem(objkey);

            if(ordersList){
                var orders = JSON.parse(ordersList);
                if (orders['spec_'+specid]) {
                    orders['spec_'+specid]['staff_ids'] = _serveids;
                    // orders['spec_'+specid]['staff_img'] = staffimg;
                    orders['spec_'+specid]['staff_name'] = staffnames;
                    var serializedArray = JSON.stringify(orders);
                    sessionStorage.setItem(objkey, serializedArray);
                }
            }
        }
        $('#chooseServerModal').modal('hide');
    });

    //商品分类数据加载
    $(document).on("click", ".list-group-item-action", function () {
        var searchword = $.trim($(".search-word").val());
        var cateid = $(this).data('cateid');
        var datatype = $(this).data('datatype');
        initdata(datatype,cateid,searchword);
    });

    //商品分类数据加载
    $(document).on("click", ".btn-item", function () {
        var searchword = $.trim($(".search-word").val());
        $(".btn-item").removeClass('active-btn-item');
        var datatype = $(this).data('datatype');
        initdata(datatype);
        $(this).addClass('active-btn-item');
    });

    //筛选商品
    $(document).on("click", ".search-btn", function () {
        var searchword = $.trim($(".search-word").val());
        var datatype = $(".active").data('datatype');
        var cateid = $(".active").data('cateid');
        initdata(datatype,cateid,searchword);
    });

    //关闭本单
    $(document).on("click", ".close-curorder", function () {
        var datatype = $(".active-btn-item").data("datatype");
        var customerinfo = sessionStorage.getItem('customer');
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;

            //清除客户信息
            sessionStorage.removeItem('customer');

            if (datatype == 'cards') {
                //清除用户订单信息
                var goodsorder = sessionStorage.getItem('cardsorder_'+user_id);
                if (goodsorder && goodsorder.length != 0) {
                    sessionStorage.removeItem('cardsorder_'+user_id);
                }

                //清除用户订单统计信息
                var goodsordercount = sessionStorage.getItem('cardsordercount_'+user_id);
                if (goodsordercount && goodsordercount.length != 0) {
                    sessionStorage.removeItem('cardsordercount_'+user_id);
                }
            }else{
                //清除用户订单信息
                var goodsorder = sessionStorage.getItem('goodsorder_'+user_id);
                if (goodsorder && goodsorder.length != 0) {
                    sessionStorage.removeItem('goodsorder_'+user_id);
                }

                //清除用户订单统计信息
                var goodsordercount = sessionStorage.getItem('goodsordercount_'+user_id);
                if (goodsordercount && goodsordercount.length != 0) {
                    sessionStorage.removeItem('goodsordercount_'+user_id);
                }
            }
        }
        //刷新页面数据
        initdata(datatype);
    });

    //挂单本单
    $(document).on("click", ".registration-curorder", function () {
        var datatype = $(".active-btn-item").data("datatype");
        var customerinfo = sessionStorage.getItem('customer');
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;

            //清除客户信息
            sessionStorage.removeItem('customer');
        }
        //刷新页面数据
        initdata(datatype);
    });

    //查看耗卡
     $(document).on("click", ".show-my-card", function () {
        var customerinfo = sessionStorage.getItem('customer');
        if(!customerinfo || customerinfo.length == 0){
            layer.open({
                title:'提示信息',
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">客户不存在，请先选择客户！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    layer.close(index);
                }
            });
            return false;
        };

        var user_info = JSON.parse(customerinfo);
        var user_id = user_info.id;
        //查询会员卡项
        //获取用户权益卡
        $.ajax({
            type: 'POST',
            url: '/cashdesk/index/getmyordercards',
            dataType: "json",
            data: {userid:user_id},
            success: function (ret) {
                if (ret.code != 1) {
                    layer.open({
                        type: 1,
                        title:'提示信息',
                        area: ['280px', '180px'],
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">暂无可用权益卡，请先去购买吧！</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                        }
                    });
                    return false;
                }else{
                    var cards_list = ret.data;
                    var cards_html = '';
                    $(".user-card-item-list").html("");
                    if(cards_list.length != 0){
                        for (var i = 0; i < cards_list.length; i++) {

                            if (cards_list[i]['type'] != 4) {
                                var cardid = cards_list[i]['id'];
                                cards_html += '<div class="row card-item card-common card-item-actives" data-cardid="'+cards_list[i]['id']+'" data-unitprice="'+cards_list[i]['unit_price']+'">';
                                cards_html += '<div class="row col-sm-12 card-common">';
                                cards_html += '<div class="col-sm-10 card-name"><span>'+cards_list[i]['name']+'</span></div>';
                                cards_html += '<div class="col-sm-2 card-times"><span>'+Number(cards_list[i]['spent'])+'/'+cards_list[i]['total']+'</span></div>';
                                cards_html += '</div>';
                                cards_html += '<div class="row col-sm-12 card-common">';
                                cards_html += '<div class="col-sm-12 card-price"><span>(总价:￥'+ parseFloat(cards_list[i]['price']).toFixed(2)+')</span>&nbsp;&nbsp;&nbsp;&nbsp;<span>(耗卡:￥'+ parseFloat(cards_list[i]['unit_price']).toFixed(2)+')</span></div>';
                                cards_html += '</div>';
                                cards_html += '<div class="row col-sm-12 card-common card-desc"><span>项目：'+cards_list[i]['card_service']+'</span></div>';
                                cards_html += '<div class="row col-sm-12 card-common card-detail">';
                                cards_html += '<div class="col-sm-2">'+cards_list[i]['type_name']+'</div>';
                                cards_html += '<div class="col-sm-6">有效期：<span class="exp-endtime">'+cards_list[i]['time']+'</span></div>';
                                cards_html += '<div class="col-sm-4 cards-operate">';
                                cards_html += '<span>';
                                cards_html += '</span>';
                                cards_html += '</div>';
                                cards_html += '</div>';
                                cards_html += '</div>';
                            }else{
                                var cardid = cards_list[i]['card_id'];
                                var spent_money = parseFloat(parseFloat(cards_list[i]['spent']) + parseFloat(cards_list[i]['gift'])).toFixed(2);
                                cards_html += '<div class="row card-item card-common card-item-actives" data-cardid="'+cards_list[i]['id']+'">';
                                cards_html += '<div class="row col-sm-12 card-common">';
                                cards_html += '<div class="col-sm-8 card-name"><span>'+cards_list[i]['name']+'</span></div>';
                                cards_html += '<div class="col-sm-4 card-times"><span>￥'+spent_money+'</span></div>';
                                cards_html += '</div>';
                                cards_html += '<div class="row col-sm-12 card-common card-desc"><span></span></div>';
                                cards_html += '<div class="row col-sm-12 card-common card-detail">';
                                cards_html += '<div class="col-sm-4">'+cards_list[i]['type_name']+'</div>';
                                cards_html += '<div class="col-sm-8">有效期：<span class="exp-endtime">'+cards_list[i]['time']+'</span></div>';
                                cards_html += '<div class="col-sm-4 cards-operate">';
                                cards_html += '<span>';
                                cards_html += '</span>';
                                cards_html += '</div>';
                                cards_html += '</div>';
                                cards_html += '</div>';
                            }
                        }
                    }

                    if(cards_html != ''){
                        $(".user-card-item-list").html(cards_html);

                        $('#userCardListModal').modal('show');
                        cards_html = '';
                    }
                }
            },
            error: function (ret) {
                layer.open({
                    type: 1, 
                    area: ['280px', '180px'],
                    title:'提示信息',
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        // 点击确定按钮后的回调函数
                        // index是弹窗的索引，layero是弹窗的DOM对象
                        layer.close(index); // 关闭弹窗
                    }
                });
            }
        });
        $('#userCardListModal').modal('show');
    });


    //挂单----获取订单列表
    $(document).on("click", ".label-btn-registration", function () {
        var datatype = $(".active-btn-item").data("datatype");
        var orders = {};
        var objkey = 'goodsorder';
        if (datatype == "cards") {
            objkey = 'cardsorder';
        }

        orders = getItemsByKeyword(objkey+'_');
        if (orders && orders.length > 0) {
            var insertHtml = '';
            for (var key in orders) {
                var kkey = orders[key]['key'];//goodsorder_36
                var user_id = kkey.substring(11);

                //获取用户信息
                var customer = sessionStorage.getItem('user_'+user_id);

                //订单信息
                var orderList = JSON.parse(orders[key]['value']);

                if(customer && customer.length != 0 && orderList){
                    //用户信息
                    var user_info = JSON.parse(customer);

                    //订单金额统计
                    var ordersCount =  sessionStorage.getItem(objkey+'count_'+user_id);
                    var count_info = JSON.parse(ordersCount);

                    var ordersListHtml = '';
                    
                    $('.order-items').html('');

                    var count = Object.getOwnPropertyNames(orderList).length;
                    if (count > 0) {
                        ordersListHtml += '<div class="row order-item-list">';
                        ordersListHtml += '<div class="row" style="margin-left: 0;">';
                        ordersListHtml += '<div class="col-md-8">';
                        ordersListHtml += '<div class="row" style="float: left;">';
                        ordersListHtml += '<img class="goods-img" src="'+user_info.avatar+'" alt="">';
                        ordersListHtml += '</div>';
                        ordersListHtml += '<div class="row user-info-detail">';
                        ordersListHtml += '<div class="col-md-12">';
                        ordersListHtml += '<p>'+user_info.nickname+'</p>';
                        ordersListHtml += '<p>'+user_info.mobile+'</p>';
                        ordersListHtml += '</div>';
                        ordersListHtml += '</div>';
                        ordersListHtml += '</div>';
                        ordersListHtml += '<div class="col-md-4">';
                        ordersListHtml += '<label class="label label-btns label-btn col-sm-2 cancel-order" data-orderno="'+kkey+'">取消</label>';
                        ordersListHtml += '<label class="label label-btns label-btn col-sm-2 settlement-order" data-orderno="'+kkey+'">结算</label>';
                        ordersListHtml += '</div>';
                        ordersListHtml += '</div>';
                        for (var key1 in orderList) {
                            ordersListHtml += '<div class="row order-items">';
                            if(orderList[key1]['datatype'] == 'cards'){
                                ordersListHtml += '<div class="col-md-9 order-goods-title">'+orderList[key1]['spec_name']+'(数量：'+orderList[key1]['spec_number']+')</div>';
                            }else{
                                ordersListHtml += '<div class="col-md-9 order-goods-title">'+orderList[key1]['goods_name']+'(规格：'+orderList[key1]['spec_name']+')(数量：'+orderList[key1]['spec_number']+')</div>';
                            }
                            ordersListHtml += '<div class="col-md-3 order-goods-price">￥'+orderList[key1]['spec_price']+'</div>';
                            ordersListHtml += '</div>';
                        }
                        ordersListHtml += '<div class="row order-items">';
                        ordersListHtml += '<div class="col-md-6 order-goods-title">........</div>';
                        ordersListHtml += '<div class="col-md-6 order-goods-price">共'+count+'项</div>';
                        ordersListHtml += '</div><div class="order-items-divider"></div><div class="row order-items"><div class="col-md-6"></div>';
                        ordersListHtml += '<div class="col-md-6 order-total-div">合计：<span class="order-total-price">￥'+count_info['totalfee']+'</span></div></div></div>';
                        insertHtml += ordersListHtml;
                    }
                }
            }
            $('.order-items').html(insertHtml);
            $('#orderListModal').modal('show');
        }
    });

    //挂单列表--取消操作
    $(document).on("click", ".cancel-order", function () {
        var datatype = $(".active-btn-item").data("datatype");
        var key = $(this).data('orderno');
        var user_id = key.substring(11);
        if(user_id){
            var customerinfo = sessionStorage.getItem('customer');
            if(customerinfo && customerinfo.length != 0){
                var user_info = JSON.parse(customerinfo);
                if (user_info.id == user_id) {
                    //清除客户信息
                    sessionStorage.removeItem('customer');
                }
            }

            var orderkey = 'goodsorder_'+user_id;
            var countkey = 'goodsordercount_'+user_id;
            if (datatype == 'cards') {
                orderkey = 'cardsorder_'+user_id;
                countkey = 'cardsordercount_'+user_id;
            }

            //清除用户订单信息
            var goodsorder = sessionStorage.getItem(orderkey);
            if (goodsorder && goodsorder.length != 0) {
                sessionStorage.removeItem(orderkey);
            }

            //清除用户订单统计信息
            var goodsordercount = sessionStorage.getItem(countkey);
            if (goodsordercount && goodsordercount.length != 0) {
                sessionStorage.removeItem(countkey);
            }
        }
        $('#orderListModal').modal('hide');
        //刷新页面数据
        initdata(datatype);
    });

    //挂单列表--结算操作
    $(document).on("click", ".settlement-order", function () {
        var key = $(this).data('orderno');
        var user_id = key.substring(11);

        var userinfo = sessionStorage.getItem('user_'+user_id);
        if(userinfo){
            var user_info = JSON.parse(userinfo);
            //更新用户信息
            var serializedArray = JSON.stringify(user_info);
            sessionStorage.setItem('customer', serializedArray);
        }
        $('#orderListModal').modal('hide');

        window.location = 'cashdesk/index/order';

    });

    //清空购物车商品
    $(document).on("click", ".label-btn-clear-all", function () {
        $(".cart-list").html("");
        var datatype = $(".active-btn-item").data("datatype");
        var customerinfo =  sessionStorage.getItem('customer');

        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;

            //获取订单信息和订单统计
            var orderkey = 'goodsorder_'+user_id;
            if (datatype == 'cards') {
                orderkey = 'cardsorder_'+user_id;
            }
            var goodsorder = sessionStorage.getItem(orderkey);
            if(goodsorder){
                //更新订单列表
                var serializedArray = JSON.stringify({});
                sessionStorage.setItem(orderkey, serializedArray);
            }
        }
        updateorderdetail(datatype);
    });

    //删除购物车商品
    $(document).on("click", ".del-item-icon", function () {
        var spec_id = $(this).data('specid');
        var customerinfo =  sessionStorage.getItem('customer');
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;
            var goodsorder = sessionStorage.getItem('goodsorder_'+user_id);
            var orders = JSON.parse(goodsorder);
            var key = 'spec_'+spec_id;
            if(orders[key]){
                delete orders[key];

                //更新订单列表
                var serializedArray = JSON.stringify(orders);
                sessionStorage.setItem('goodsorder_'+user_id, serializedArray);
            }
        }

        $(this).parents(".card-item").remove();
        updateorderdetail(); 
    });

    //删除购物车商品
    $(document).on("click", ".del-card-icon", function () {
        var spec_id = $(this).data('specid');
        var customerinfo =  sessionStorage.getItem('customer');
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;
            var goodsorder = sessionStorage.getItem('cardsorder_'+user_id);
            var orders = JSON.parse(goodsorder);
            var key = 'spec_'+spec_id;
            if(orders[key]){
                delete orders[key];

                //更新订单列表
                var serializedArray = JSON.stringify(orders);
                sessionStorage.setItem('cardsorder_'+user_id, serializedArray);
            }
        }

        $(this).parents(".cards-item").remove();
        updateorderdetail('cards'); 
    });

    //改价
    $(document).on("click", ".edit-price-icon", function () {
        var specid = $(this).data('specid');
        var customerinfo =  sessionStorage.getItem('customer');
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var goodsorder = sessionStorage.getItem('goodsorder_'+user_info.id);
            var orders = JSON.parse(goodsorder);
            var price = orders['spec_'+specid]['spec_price'];
        
            $(".change_price_specid").val(specid);
            $(".goodsprice").html(price);
            $('#changePriceModal').modal('show');
        }
    });

    //改价(更改订单金额)
    $(document).on("click", ".change-price", function () {
        var datatype = $(".active-btn-item").data("datatype");
        var customerinfo =  sessionStorage.getItem('customer');

        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;

            //获取订单信息和订单统计
            var orderkey = 'goodsordercount_'+user_id;
            if (datatype == 'cards') {
                orderkey = 'cardsordercount_'+user_id;
            }

            var orderCount = sessionStorage.getItem(orderkey);
            var ordersCount = JSON.parse(orderCount);

            $(".oldorderfee").text(ordersCount['totalfee']);
            $(".change_orderno").val(orderkey);
            $('#changeOrderPriceModal').modal('show');
        }
    });

    //确认修改价格
    $(document).on("click", ".btn-change-price", function () {
        var specid = $(".change_price_specid").val();
        var newprice = $('.change-price-text').val();
        var price = parseFloat(newprice).toFixed(2);//新价

        $('.trdata[data-id="'+specid+'"]').attr('data-price',parseFloat(price).toFixed(2));
        $('.trdata[data-id="'+specid+'"]').find('.card-text-price').html('￥ '+parseFloat(price).toFixed(2));
        var customerinfo =  sessionStorage.getItem('customer');
        var user_info = JSON.parse(customerinfo);
        var user_id = user_info.id;
        var ordersList = sessionStorage.getItem('goodsorder_'+user_id);
        if(ordersList){
            var orders = JSON.parse(ordersList);
            orders['spec_'+specid]['spec_price'] = price;
            var serializedArray = JSON.stringify(orders);
            sessionStorage.setItem('goodsorder_'+user_id, serializedArray);
        }

        updateDiscountFee(user_id);

        $('.change-price-text').val("0");
        $('#changePriceModal').modal('hide');
        updateorderdetail();
    });

    //确认修改订单总金额
    $(document).on("click", ".btn-change-orderfee", function () {
        var orderno = $(".change_orderno").val();
        var datatype = orderno.substring(0,5);
        var user_id = orderno.substring(16);
        var orderkey = datatype+'order_'+user_id;
        var neworderfee = $('.change-orderfee-text').val();
        var totalfee = parseFloat(neworderfee).toFixed(2);//新价

        $('.ordertotalfee').text(totalfee);
        var orderCount = sessionStorage.getItem(orderno);
        if(orderCount){
            var count = JSON.parse(orderCount);
            var originalfee = count['totalfee'];
            count['modifyfee'] = totalfee;
            var order_list = sessionStorage.getItem(orderkey);
            if (order_list) {
                var orders = JSON.parse(order_list);
                for(var k in orders){
                    var spec_newprice = parseFloat((orders[k]['spec_price']*orders[k]['spec_number']/originalfee)*totalfee/orders[k]['spec_number']).toFixed(2);
                    orders[k]['spec_price'] = spec_newprice;
                }
                //更新订单金额
                var serializedArray = JSON.stringify(orders);
                sessionStorage.setItem(orderkey, serializedArray);
            }

            var serializedArray = JSON.stringify(count);
            sessionStorage.setItem(orderno, serializedArray);
        }

        updateDiscountFee(user_id);

        $('.change-orderfee-text').val("0");
        $('#changeOrderPriceModal').modal('hide');
        initdata(datatype);
    });

    //收款
    $(document).on("click", ".pay-order", function () {
        var customerinfo = sessionStorage.getItem('customer');
        // if(!customerinfo || customerinfo.length == 0){
        //     layer.open({
        //         title:'警告',
        //         type: 1, 
        //         area: ['280px', '180px'],
        //         content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">客户不存在，请先选择客户！</p>',
        //         btn: ['确定'], // 弹窗按钮
        //         btnAlign:"c",
        //         yes: function(index, layero){
        //             layer.close(index);
        //         }
        //     });
        //     $(".btn-operate-order").attr('disabled',true);
        //     return false;
        // };

        var user_info = JSON.parse(customerinfo);
        var user_id = user_info.id;

        var currentkey = sessionStorage.getItem('currentkey');
        if (currentkey) {
            var current_key = JSON.parse(currentkey);
            data_type = current_key['datatype'];
        }

        var countkey = 'goodsordercount_'+user_id;
        if (data_type == "cards") {
            countkey = 'cardsordercount_'+user_id;
        }

        var orderCount =  sessionStorage.getItem(countkey);
        // if(!orderCount){
        //     layer.open({
        //         title:'警告',
        //         type: 1, 
        //         area: ['280px', '180px'],
        //         content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">请先选择商品后再去结算！</p>',
        //         btn: ['确定'], // 弹窗按钮
        //         btnAlign:"c",
        //         yes: function(index, layero){
        //             layer.close(index);
        //         }
        //     });
        //     $(".btn-operate-order").attr('disabled',true);
        //     return false;
        // }

        var orderAmount = JSON.parse(orderCount);
        // if (!orderAmount['totalfee'] || orderAmount['totalfee'] == 0) {
        //     layer.open({
        //         title:'警告',
        //         type: 1, 
        //         area: ['280px', '180px'],
        //         content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">请先选择商品后再去结算！</p>',
        //         btn: ['确定'], // 弹窗按钮
        //         btnAlign:"c",
        //         yes: function(index, layero){
        //             layer.close(index);
        //         }
        //     });
        //     $(".btn-operate-order").attr('disabled',true);
        //     return false;
        // }
        
        window.location = 'cashdesk/index/order';
    });

    //选择权益卡
    $(document).on("click", ".card-equitycard-operate", function () {
        var specid = $(this).data('specid');
        var customerinfo =  sessionStorage.getItem('customer');
        var user_info = JSON.parse(customerinfo);
        var user_id = user_info.id;
        var orderlist = sessionStorage.getItem('goodsorder_'+user_id);
        var orders = {};
        if (orderlist) {
            orders = JSON.parse(orderlist);
        }

        //获取用户权益卡
        $.ajax({
            type: 'POST',
            url: '/cashdesk/index/getusercards',
            dataType: "json",
            data: {userid:user_id,specid:specid},
            success: function (ret) {
                if (ret.code != 1) {
                    layer.open({
                        type: 1,
                        title:'提示信息',
                        area: ['280px', '180px'],
                        content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">暂无可用权益卡，请先去购买吧！</p>',
                        btn: ['确定'], // 弹窗按钮
                        btnAlign:"c",
                        yes: function(index, layero){
                            // 点击确定按钮后的回调函数
                            // index是弹窗的索引，layero是弹窗的DOM对象
                            layer.close(index); // 关闭弹窗
                        }
                    });
                    return false;
                }else{
                    var cards_list = ret.data;
                    var cards_html = '';
                    $(".card-item-list").html("");
                    if(cards_list.length != 0){
                        for (var i = 0; i < cards_list.length; i++) {
                            var cardid = cards_list[i]['id'];
                            cards_html += '<div class="row card-item card-common card-item-active" data-cardid="'+cards_list[i]['id']+'" data-unitprice="'+cards_list[i]['unit_price']+'">';
                            cards_html += '<div class="row col-sm-12 card-common">';
                            cards_html += '<div class="col-sm-8 card-name"><span>'+cards_list[i]['name']+'</span><span style="color:#fe234f">(耗卡:￥'+ parseFloat(cards_list[i]['unit_price']).toFixed(2)+')</span></div>';
                            cards_html += '<div class="col-sm-4 card-times"><span>'+cards_list[i]['spent']+'/'+cards_list[i]['total']+'</span></div>';
                            cards_html += '</div>';
                            if (cards_list[i]['card_service'] == '') {
                                cards_html += '<div class="row col-sm-12 card-common card-desc"><span></span></div>'; 
                           }else{
                                cards_html += '<div class="row col-sm-12 card-common card-desc"><span>项目：'+cards_list[i]['card_service']+'</span></div>';
                           }
                            
                            cards_html += '<div class="row col-sm-12 card-common card-detail">';
                            cards_html += '<div class="col-sm-2">'+cards_list[i]['type_name']+'</div>';
                            cards_html += '<div class="col-sm-6">有效期：<span class="exp-endtime">'+cards_list[i]['time']+'</span></div>';
                            cards_html += '<div class="col-sm-4 cards-operate">';
                            cards_html += '<span>';
                            cards_html += '<input type="button" class="card-reduce-action" value="-" onclick="modityMyCardsNum($(this))" />';
                            if(orders && orders['spec_'+specid]['cards'] && orders['spec_'+specid]['cards'][cardid]){
                                var cardnumber = orders['spec_'+specid]['cards'][cardid];
                                cards_html += '<input type="number" max="'+cards_list[i]['spent']+'" min="0" step="1" class="buy-cards-quantity" value="'+cardnumber+'" />';
                            }else{
                                cards_html += '<input type="number" max="'+cards_list[i]['spent']+'" min="0" step="1" class="buy-cards-quantity" value="0" />';
                            }
                            
                            cards_html += '<input type="button" class="card-incr-action" value="+" onclick="modityMyCardsNum($(this),\'incr\')"/>';
                            cards_html += '</span>';
                            cards_html += '</div>';
                            cards_html += '</div>';
                            cards_html += '</div>';
                        }
                    }

                    if(cards_html != ''){
                        $(".card-item-list").html('');
                        $(".card-item-list").append(cards_html);
                        $('.btn-choose-cards').removeData('specid');
                        $('.btn-choose-cards').data('specid', specid);
                        $('.btn-choose-cards').attr('data-specid', specid);

                        $('.btn-choose-cards').removeData('userid');
                        $('.btn-choose-cards').data('userid', user_id);
                        $('.btn-choose-cards').attr('data-userid', user_id);


                        $('#myCardListModal').modal('show');
                        cards_html = '';
                    }else{
                        $(".card-item-list").html('');
                         $('.btn-choose-cards').removeData('specid');
                        $('.btn-choose-cards').data('specid', '');
                        $('.btn-choose-cards').attr('data-specid', 0);

                        $('.btn-choose-cards').removeData('userid');
                        $('.btn-choose-cards').data('userid', 0);
                        $('.btn-choose-cards').attr('data-userid', 0);
                    }
                }
            },
            error: function (ret) {
                layer.open({
                    type: 1, 
                    area: ['280px', '180px'],
                    title:'提示信息',
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+ret.msg+'</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        // 点击确定按钮后的回调函数
                        // index是弹窗的索引，layero是弹窗的DOM对象
                        layer.close(index); // 关闭弹窗
                    }
                });
            }
        });
        
        return false;
    });

    $(document).on("input", ".add_amount", function () {
        var recharge_amount = parseFloat($(this).val()).toFixed(2);
        var customerinfo = sessionStorage.getItem('customer');
        var user_id = 0;
        var data_type = 'goods';
        var currentkey = sessionStorage.getItem('currentkey');
        if (currentkey) {
            var current_key = JSON.parse(currentkey);
            data_type = current_key['datatype'];
        }
        var user_info = JSON.parse(customerinfo);
        user_id = user_info.id;

        var orderkey = 'goodsorder_'+user_id;
        if (data_type == 'cards') {
            orderkey = 'cardsorder_'+user_id;
        }
        var pobj = $(this).parents(".cards-item");
        var id = pobj.data("id");
        var ordersList = sessionStorage.getItem(orderkey);
        if (recharge_amount != 0 && ordersList) {
            var orders = JSON.parse(ordersList);
            if (orders && orders['spec_'+id]) {
                orders['spec_'+id]['spec_price'] = recharge_amount;
                var serializedArray = JSON.stringify(orders);
                sessionStorage.setItem(orderkey, serializedArray);
            }
        }
        updateorderdetail(data_type);
        return false;
    });

    $(document).on("input", ".gift_amount", function () {
        var gift_amount = parseFloat($(this).val()).toFixed(2);
        var customerinfo = sessionStorage.getItem('customer');
        var user_id = 0;
        var data_type = 'goods';
        var currentkey = sessionStorage.getItem('currentkey');
        if (currentkey) {
            var current_key = JSON.parse(currentkey);
            data_type = current_key['datatype'];
        }
        var user_info = JSON.parse(customerinfo);
        user_id = user_info.id;

        var orderkey = 'goodsorder_'+user_id;
        if (data_type == 'cards') {
            orderkey = 'cardsorder_'+user_id;
        }
        var pobj = $(this).parents(".cards-item");
        var id = pobj.data("id");
        var ordersList = sessionStorage.getItem(orderkey);
        if (gift_amount != 0 && ordersList) {
            var orders = JSON.parse(ordersList);
            if (orders && orders['spec_'+id]) {
                orders['spec_'+id]['gift_price'] = gift_amount;
                var serializedArray = JSON.stringify(orders);
                sessionStorage.setItem(orderkey, serializedArray);
            }
        }
        updateorderdetail(data_type);
        return false;
    });
    //商品数量更新后提示
    $(document).on("input", ".buy-quantity", function () {
        var data_type = $(this).data('type');
        var max = parseInt($(this).attr('max'), 10);
        var currentValue = parseInt($(this).val(), 10) || 0;
        //更新购物车数据
        var customerinfo = sessionStorage.getItem('customer');
        var user_id = 0;
        var changed_number = 0;

        if(!customerinfo || customerinfo.length == 0){
            layer.open({
                title:'提示信息',
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">客户不存在，请先选择客户！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    layer.close(index);
                }
            });
            return false;
        };

        var user_info = JSON.parse(customerinfo);
        user_id = user_info.id;

        var orderkey = 'goodsorder_'+user_id;
        if (data_type == 'cards') {
            orderkey = 'cardsorder_'+user_id;
        }

        var ordersList = sessionStorage.getItem(orderkey);

        if (currentValue >= max) {
            $(this).val(max); // 限制输入值为最大值
            changed_number = max;
            if (data_type == 'goods') {
                $(this).next(".available-action").addClass("unavailable-action");
                $(this).prev(".available-action").removeClass("unavailable-action");
            }
        } else if(currentValue <= 0){
            $(this).val(0); // 输入值合法时隐藏警告
            changed_number = 0;
            if (data_type == 'goods') {
                $(this).prev(".available-action").addClass("unavailable-action");
                $(this).next(".available-action").removeClass("unavailable-action");
            }
        }else{
            changed_number = currentValue;
            if (data_type == 'goods') {
                $(this).prev(".available-action").removeClass("unavailable-action");
                $(this).next(".available-action").removeClass("unavailable-action");
            }
        }

        if (changed_number != 0) {
            if($(this).parents(".trdata") != undefined && ordersList){
                var id = $(this).parents(".trdata").data("id");
                var orders = JSON.parse(ordersList);
                if (orders && orders['spec_'+id]) {
                    orders['spec_'+id]['spec_number'] = changed_number;
                    var serializedArray = JSON.stringify(orders);
                    sessionStorage.setItem(orderkey, serializedArray);
                }
            }
        }else{
            if($(this).parents(".trdata") != undefined && ordersList){
                if (data_type == 'cards') {
                    var orders = JSON.parse(ordersList);
                    var key = 'spec_'+spec_id;
                    if(orders[key]){
                        delete orders[key];

                        //更新订单列表
                        var serializedArray = JSON.stringify(orders);
                        sessionStorage.setItem(orderkey, serializedArray);
                    }
                    $(this).parents(".card-item").remove();
                }else{
                    var id = $(this).parents(".trdata").data("id");
                    $('.del-item-icon[data-specid="'+id+'"]').click();
                }
            }
        }
        updateorderdetail(data_type);
        return false;
    });

    //修改商品数量到购物车
    window.modityGoodsNum =  function(obj,operate='reduce',need_up=0){
        //商品id
        var goodsid = obj.parents('.trdata').data('goodsid');
        //属性id
        var id = obj.parents('.trdata').data('id');
        //当前属性下商品的库存
        var stock = obj.parents('.trdata').data('stock');
        //当前商品数量
        var cur_num = parseInt(obj.parents('.trdata').find(".buy-quantity").val());
        var changed_number = 0;
        if($.inArray(operate, ['reduce','incr']) == -1){
            layer.open({
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">操作失败，请稍后重试！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    // 点击确定按钮后的回调函数
                    // index是弹窗的索引，layero是弹窗的DOM对象
                    layer.close(index); // 关闭弹窗
                }
            });
        }else if(operate=='reduce'){//减少
            changed_number = parseInt(cur_num-1);
            if(changed_number <= 0){
                changed_number = 0;
                obj.addClass('unavailable-action');
            }else{
                obj.removeClass('unavailable-action');
            }
            obj.next(".buy-quantity").next(".incr-action").removeClass('unavailable-action');
            obj.next(".buy-quantity").val(changed_number);

            if (changed_number == 0) {
                $('.del-item-icon[data-specid="'+id+'"]').click();
            }
        }else if(operate=='incr'){//增加
            changed_number = parseInt(cur_num+1);
            if(changed_number >= stock){
                changed_number = stock;
                obj.addClass('unavailable-action');
            }else{
                obj.removeClass('unavailable-action');
            }
            obj.prev(".buy-quantity").prev(".reduce-action").removeClass('unavailable-action');
            obj.prev(".buy-quantity").val(changed_number);
        }
        //更新购物车数据
        var customerinfo =  sessionStorage.getItem('customer');
        var user_id = 0;
        if(customerinfo && customerinfo.length != 0 && need_up == 1){
            var user_info = JSON.parse(customerinfo);
            user_id = user_info.id;
            var ordersList = sessionStorage.getItem('goodsorder_'+user_id);
            if(ordersList){
                var orders = JSON.parse(ordersList);
                if (orders && orders['spec_'+id]) {
                    orders['spec_'+id]['spec_number'] = changed_number;
                    var serializedArray = JSON.stringify(orders);
                    sessionStorage.setItem('goodsorder_'+user_id, serializedArray);
                }
            }
        }

        updateorderdetail();
        return false;
    }

    //修改卡项数量到购物车
    window.modityCardsNum =  function(obj,operate='reduce'){
        //获取用户信息
        var customerinfo =  sessionStorage.getItem('customer');
        if(!customerinfo || customerinfo.length == 0){
            layer.open({
                title:'提示信息',
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">客户不存在，请先选择客户！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    layer.close(index);
                }
            });
            return false;
        };

        //卡项id
        var spec_id = obj.parents('.cards-item-div').data('id');
        //分类id
        var cateid = obj.parents('.cards-item-div').data('cateid');
        //当前商品数量
        var cur_num = parseInt(obj.parents('.cards-item-div').find(".buy-quantity").val());
        var changed_number = 0;
        if($.inArray(operate, ['reduce','incr']) == -1){
            layer.open({
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">操作失败，请稍后重试！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    // 点击确定按钮后的回调函数
                    // index是弹窗的索引，layero是弹窗的DOM对象
                    layer.close(index); // 关闭弹窗
                }
            });
        }else if(operate=='reduce'){//减少
            var changed_number = parseInt(cur_num-1);
            if(changed_number <= 0){
                changed_number = 0;
            }
            obj.next(".buy-quantity").val(changed_number);
        }else if(operate=='incr'){//增加
            var changed_number = parseInt(cur_num+1);
            obj.prev(".buy-quantity").val(changed_number);
        }
        //更新购物车数据
        var user_info = JSON.parse(customerinfo);
        var objkey = 'cardsorder_'+user_info.id;

        var cardsorder = {};
        var orderList =  sessionStorage.getItem(objkey);
        if(orderList){
            cardsorder = JSON.parse(orderList);
        }

        var need_up = obj.parents('.cards-item-div').data('needupdate');
        var cateid = obj.parents('.cards-item-div').data('cateid');
        if (need_up == 1) {
            cardsorder['spec_'+spec_id]['spec_number'] = changed_number;
            var serializedArray = JSON.stringify(cardsorder);
            sessionStorage.setItem('cardsorder_'+user_info.id, serializedArray);
        }else{
            var cart_cards_html = '';

            if (changed_number > 0 && (cardsorder['spec_'+spec_id] == null || Object.entries(cardsorder['spec_'+spec_id]).length == 0)){
                //卡项名称
                var spec_name = obj.parents('.cards-item').find('.cards-item-info-name').text();
                //卡项内容
                var spec_service = obj.parents('.cards-item').find('.cards-item-info-content').text();
                //卡项价格
                var spec_price = obj.parents('.cards-item').find('.cards-item-info-price').text();
                //卡项vip价格
                var vip_price = 0;
                if (obj.parents('.cards-item').find('.vip_price').length > 0) {
                    vip_price = obj.parents('.cards-item').find('.vip_price').text();
                }
                //卡项数量
                var spec_number = obj.parents('.cards-item').find('.buy-quantity').val();
                //卡项有效期
                var spec_expiration = obj.parents('.cards-item').find('.cards-item-lifespan-expiration').text();
                //卡项次数
                var spec_total = obj.parents('.cards-item').find('.cards-item-lifespan-times').text();
                //卡项类型
                var spec_type = obj.parents('.cards-item').find('.cards-item-detail-title').text();

                if (user_info.level > 1 && parseFloat(vip_price).toFixed(2) != 0.00) {
                    spec_price = vip_price;
                }

                var add_amount = spec_price;
                if (cateid == 6) {
                   add_amount = 0;
                }
                cardsorder['spec_'+spec_id] = {
                    spec_id:spec_id,
                    cateid:cateid,
                    spec_name:spec_name,
                    datatype:'cards',
                    spec_price:add_amount,
                    old_spec_price:spec_price,
                    gift_price:0,
                    spec_originalprice:add_amount,
                    spec_discountfee:0,
                    uprice:0,
                    spec_number:spec_number,
                    spec_service:add_amount,
                    spec_expiration:spec_expiration,
                    spec_total:spec_total,
                    spec_type:spec_type,
                }
                cart_cards_html += '<div class="col-md-5 cards-item cards-item-div" data-cateid="'+cateid+'" data-id="'+spec_id+'" data-needupdate="1"  data-type="cards" style="width:100%;">';
                cart_cards_html += '<div class="row cards-item-info">';
                cart_cards_html += '<div class="col-md-8" style="padding-left:0px;font-weight: bold;font-size: 18px;"><span class="cards-item-info-name">'+spec_name+'</span></div>';
                cart_cards_html += '<div class="col-md-4" style="font-size: 20px;text-align:right;color:#fe234f;font-weight: bold;">￥<span class="cards-item-info-price">'+spec_price+'</span></div></div>';
                if (spec_service == '') {
                    cart_cards_html += '<div class="row" style="margin-left: 0px;margin-bottom: 15px;font-size: 14px;"></div>';
                }else{
                    cart_cards_html += '<div class="row" style="margin-left: 0px;margin-bottom: 15px;font-size: 14px;">项目：<span class="cards-item-info-content">'+spec_service+'</span></div>';
                }
                
                cart_cards_html += '<div class="row cards-item-lifespan">';
                cart_cards_html += '<div class="col-md-8" style="padding-left:0px;font-size: 14px;">';
                cart_cards_html += '有效期: <span class="cards-item-lifespan-expiration">'+spec_expiration+'</span></div>';

                cart_cards_html += '<div class="col-md-4" style="text-align:right;font-weight: bold;font-size: 16px;">';
                if (spec_total != '') {
                    cart_cards_html += '<span class="cards-item-lifespan-times">'+spec_total+'</span> 次</div></div>';
                }else{
                    cart_cards_html += '<span class="cards-item-lifespan-times"></div></div>';
                }
                
                cart_cards_html += '<div class="row cards-item-detail"><div class="col-sm-4"><span class="cards-item-detail-title">'+spec_type+'</span></div><div class="col-sm-8" style="width: auto;text-align: center;padding-left:0px;font-size: 14px;">';
                if (cateid != 6) {
                    cart_cards_html += '<input type="button" class="reduce-action" value="-" onclick="modityCardsNum($(this))"/>';
                    cart_cards_html += '<input type="number" min="0" step="1" class="buy-quantity" value="'+spec_number+'" data-type="cards"/>';
                    cart_cards_html += '<input type="button" class="incr-action" value="+" onclick="modityCardsNum($(this),\'incr\')"/>';
                }else{
                    cart_cards_html += '<div class="col-md-8" style="width: auto;text-align: center;padding-left:0px;font-size: 14px;">充值金额<span class="cards-item-lifespan-expiration"><input type="number" min="0" step="0.01" class="add_amount form-control" value="0" style="text-align:center;width:80px;"/></span></div>';
                    cart_cards_html += '<div class="col-md-8" style="width: auto;text-align: center;padding-left:0px;font-size: 14px;">赠送金额<span class="cards-item-lifespan-expiration"><input type="number" min="0" step="0.01" class="gift_amount form-control" value="0" style="text-align:center;width:80px;"/></span></div>';
                }
                cart_cards_html += '</div></div>';
                cart_cards_html += '<div class="hover-card-operate-div"><img src="'+cdnUrl+'/assets/cashdesk/img/del_icon.svg" class="del-card-icon operate-icon" data-specid="'+spec_id+'"/></div>';
                cart_cards_html += '<p class="card-text card-service"><span class="card-attendant" style="line-height: 30px;color:#ff0000;" data-specid="'+spec_id+'" data-serveid="0">选择 销售人员 </span></p>';
                cart_cards_html += '</div>';
                
                var serializedArray = JSON.stringify(cardsorder);
                sessionStorage.setItem(objkey, serializedArray);
            }else{
                obj.parents('.cards-item').find('.buy-quantity').val(0)
            }

            if (cart_cards_html != '') {
                $(".cart-list").append(cart_cards_html);
                cart_cards_html = '';
                obj.parents('.cards-item').find('.buy-quantity').val(0)
            }
        }
        updateorderdetail("cards");
        return false;
    }


    //使用权益卡抵消金额
    window.modityMyCardsNum =  function(obj,operate='reduce'){
        //获取用户信息
        var customerinfo =  sessionStorage.getItem('customer');
        if(!customerinfo || customerinfo.length == 0){
            layer.open({
                title:'提示信息',
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">客户不存在，请先选择客户！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    layer.close(index);
                }
            });
            return false;
        };

        //当前商品数量
        var changeobj = obj.parents('.card-item-active').find(".buy-cards-quantity");
        var currentValue = parseInt(changeobj.val(), 10) || 0;
        var max = parseInt(changeobj.attr('max'), 10);

        if($.inArray(operate, ['reduce','incr']) == -1){
            layer.open({
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">操作失败，请稍后重试！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    // 点击确定按钮后的回调函数
                    // index是弹窗的索引，layero是弹窗的DOM对象
                    layer.close(index); // 关闭弹窗
                }
            });
        }else if(operate=='reduce'){//减少
            var changed_number = parseInt(currentValue-1);
            if(changed_number <= 0){
                changed_number = 0;
            }else if(changed_number >= max){
                changed_number = max;
            }
            changeobj.val(changed_number);
        }else if(operate=='incr'){//增加
            var changed_number = parseInt(currentValue+1);
            if (changed_number >= max) {
                changed_number = max; // 限制输入值为最大值
            } else if(changed_number <= 0){
                changed_number = 0; // 输入值合法时隐藏警告
            }
            changeobj.val(changed_number);
        }
    }

    //选择卡项
    $(document).on('click', '.btn-choose-cards', function (e) {
        var specid = $(this).data("specid");
        var userid = $(this).data("userid");
        var orderkey = 'goodsorder_'+userid;
        var ordercountkey = 'goodsordercount_'+userid;
        var cardused = {};
        var uprice = 0.00;
        var goodsorder = sessionStorage.getItem(orderkey);

        if (goodsorder) {
            var orders = JSON.parse(goodsorder);

            var totalnumber = parseInt(orders['spec_'+specid]['spec_number']);
            var totalcount = 0;//卡项使用次数
            var listobj = $(this).parents('.modal-body').find('.card-item-active');
            listobj.each(function(index) {
                var cardid = $(this).data("cardid");
                var number = parseInt($(this).find(".buy-cards-quantity").val());
                totalcount += parseInt(number);
            });
            if (totalcount > totalnumber) {
                layer.open({
                    type: 1, 
                    area: ['290px', '200px'],
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">卡项最多使用'+totalnumber+'次，请确认后重试</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        // 点击确定按钮后的回调函数
                        // index是弹窗的索引，layero是弹窗的DOM对象
                        layer.close(index); // 关闭弹窗
                    }
                });
                $('.card-item-active').each(function(index) {
                    $(this).find(".buy-cards-quantity").val(0)
                });
                return false;
            }else{
                 $('.card-item-active').each(function(index) {
                    var cardid = $(this).data("cardid");
                    var unitprice = $(this).data("unitprice");
                    var number = parseInt($(this).find(".buy-cards-quantity").val());
                    uprice += Number(unitprice)*number;
                    if (number > 0) {
                        cardused[cardid] = number;
                    }                
                });

                orders['spec_'+specid]['cards'] = cardused;
                orders['spec_'+specid]['uprice'] = uprice;
                orders['spec_'+specid]['spec_discountfee'] = parseFloat(totalcount * orders['spec_'+specid]['spec_price']).toFixed(2);
                var serializedArray = JSON.stringify(orders);
                sessionStorage.setItem(orderkey, serializedArray);

                var cateid = $(".active").data('cateid')
                var searchword = $.trim($(".search-word").val());
                initdata('services',cateid,searchword,1);

                var g_price = $('.card-equitycard-operate[data-specid="'+specid+'"]').parents('.card-item-service').find('.trdata').data('price');
                $('.card-equitycard-operate[data-specid="'+specid+'"]').parents('.card-item-service').find('.card-text-price').html('￥ '+ g_price +' <span style="color:#000">(耗卡:￥'+ parseFloat(uprice).toFixed(2)+')</span>');
                $('.card-equitycard-operate[data-specid="'+specid+'"]').text("已选次卡");
            }
            updateorderdetail();
        }
        $('#myCardListModal').modal('hide');
        return false;
    })


    //选择商品规格
    $(document).on('click', '.goods-list-item-action', function () {
        var link_url = $(this).data('url');
        var goods_id = $(this).data('id');
        var goods_type = $(this).data('type');
        $.ajax({
            type: 'POST',
            url: link_url,
            dataType: "json",
            data: {
                id:goods_id,
                type:goods_type,
            },
            success: function (ret) {
                var goodsInfo = ret.data.goodsInfo;
                var goodsSku = ret.data.goodsSku;
                var show_html = '<div class="row goods-info-item" data-id="'+goodsInfo.id+'">';
                    show_html += '<div class="col-sm-2">';
                    show_html += '<img class="goods-img" src="'+goodsInfo.image+'" alt="">';
                    show_html += '</div>';
                    show_html += '<div class="col-sm-10">';
                    show_html += '<div class="goods-title">'+goodsInfo.title+'</div>';
                    show_html += '<div class="goods-code-title">产品编号：<span class="goods-code">'+goodsInfo.code+'</span></div>';
                    show_html += '</div>';
                    show_html += '</div>';
                    if (goodsSku.length > 0) {
                        show_html += '<table class="table table-hover goods-spec-list">';
                        $.each(goodsSku, function (key,value) {
                            show_html += '<tr class="trdata" data-goodsid="'+goods_id+'" data-id="'+value.id+'" data-stock="'+value.stock+'" data-price="'+value.price+'" data-vipprice="'+goodsInfo.vip_price+'" data-type="'+goods_type+'">';
                            show_html += '<td class="goods-spec-name">'+value.difference+'</td>';
                            show_html += '<td class="goods-spec-price">￥'+value.price+'</td>';
                            show_html += '<td class="goods-spec-stock">库存:'+value.stock+'</td>';
                            show_html += '<td>';
                            show_html += '<input type="button" class="reduce-action available-action unavailable-action" value="-" onclick="modityGoodsNum($(this))" />';
                            show_html += '<input type="number" max="'+value.stock+'" min="0" step="1" class="buy-quantity" value="0" data-type="goods"/>';
                            show_html += '<input type="button" class="incr-action available-action" value="+" onclick="modityGoodsNum($(this),\'incr\')" />';
                            show_html += '</tr>';
                        });
                        show_html += '</table>';
                    }
                $(".goods-add-body").html(show_html);
                $('#addGoodsModal').modal('show');
            },
            error: function (data) {
                layer.open({
                    type: 1, 
                    area: ['280px', '180px'],
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">'+data.msg+'</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        // 点击确定按钮后的回调函数
                        // index是弹窗的索引，layero是弹窗的DOM对象
                        layer.close(index); // 关闭弹窗
                    }
                });
            }
        });
        return false;
    });

    //添加属性商品到购物车
    $(document).on("click", ".btn-confirm-info", function () {
        //获取用户信息
        var customerinfo =  sessionStorage.getItem('customer');
        if(!customerinfo || customerinfo.length == 0){
            layer.open({
                title:'提示信息',
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">客户不存在，请先选择客户！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    layer.close(index);
                }
            });
            return false;
        };

        //用户信息
        var user_info = JSON.parse(customerinfo);
        var user_id = user_info.id;
        
        //已存在购物车商品
        var goodsorders = {};
        var orderList =  sessionStorage.getItem('goodsorder_'+user_id);
        if(orderList){
            goodsorders = JSON.parse(orderList);
        }

        var cart_goods_html = '';
        var goods_obj = $('.goods-info-item');
        //商品id
        var goods_id = goods_obj.data('id');
        //商品名称
        var goods_name = goods_obj.find('.goods-title').text();
        //产品编号
        var goods_code = goods_obj.find('.goods-code').text();
        //产品图片
        var goods_img = goods_obj.find('.goods-img').attr('src');

        $('.goods-spec-list .trdata').each(function(index) {
            var goods_spec_obj = $(this);
            //购买商品数量
            var goods_number = parseInt(goods_spec_obj.find(".buy-quantity").val());
            //属性id
            var id = goods_spec_obj.data('id');
            var key = 'spec_'+id;
            if (goods_number > 0 && (goodsorders[key] == null || Object.entries(goodsorders[key]).length == 0)){
                //属性商品库存
                var stock = goods_spec_obj.data('stock');
                //产品类别 data-type
                var datatype = goods_spec_obj.data('type');
                //属性商品价格
                var price = goods_spec_obj.data('price');
                //属性商品价格
                var vip_price = goods_spec_obj.data('vipprice');
                if (user_info.level > 1 && parseFloat(vip_price).toFixed(2) != 0.00) {
                    price = vip_price;
                }
                //属性名称
                var goods_spec_name = goods_spec_obj.find(".goods-spec-name").text();
                goodsorders['spec_'+id] = {
                    goods_id:goods_id,
                    goods_img:goods_img,
                    goods_name:goods_name,
                    spec_id:id,
                    spec_name:goods_spec_name,
                    spec_stock:stock,
                    datatype:datatype,
                    spec_originalprice:price,
                    uprice:0,
                    spec_discountfee:0,
                    spec_price:price,
                    spec_number:goods_number,
                }

                if (datatype == 'goods' || datatype == 'services') {
                    cart_goods_html += '<div class="card border card-item card-item-service" data-specid="'+id+'">';
                }

                cart_goods_html += '<div class="row card-item-row"><div class="col-md-2">';
                cart_goods_html += '<img src="'+goods_img+'" class="card-img-top img-review goods-img" alt=""></div><div class="col-md-10">';
                cart_goods_html += '<div class="card-body trdata" data-goodsid="'+goods_id+'" data-id="'+id+'" data-stock="'+stock+'" data-price="'+price+'">';
                cart_goods_html += '<h5 class="card-title">'+goods_name+'</h5>';
                cart_goods_html += '<p class="card-text-price">￥ '+price+'</p>';
                cart_goods_html += '<p class="card-text">规格：'+goods_spec_name+'<span class="card-operate"><input type="button" class="reduce-action available-action" value="-" onclick="modityGoodsNum($(this),\'reduce\',1)" style="width: 20px;height: 20px;font-size: 13px;" /><input type="number" max="'+stock+'" min="0" step="1" class="buy-quantity" value="'+goods_number+'" style="font-size:13px;" data-type="goods" /><input type="button" class="incr-action available-action" value="+" onclick="modityGoodsNum($(this),\'incr\',1)" style="width: 20px;height: 20px;font-size: 13px;" /></span></p>';

                if (datatype == 'services') {
                    cart_goods_html += '<p class="card-text card-text-service">';
                    cart_goods_html += '<span class="card-attendant" style="line-height: 30px;color:#ff0000;" data-specid="'+id+'" data-serveid="0">选择 销售人员/解痛师 </span>';
                    cart_goods_html += '<span class="card-equitycard card-equitycard-operate" data-specid="'+id+'">选择次卡</span></p>';
                }

                 if (datatype == 'goods') {
                    cart_goods_html += '<p class="card-text card-text-service">';
                    cart_goods_html += '<span class="card-attendant" style="line-height: 30px;color:#ff0000;" data-specid="'+id+'" data-serveid="0">选择 销售人员 </span></p>';
                }

                cart_goods_html += '</div></div><div class="hover-operate-div">';
                cart_goods_html += '<img src="'+cdnUrl+'/assets/cashdesk/img/edit_icon.svg" class="edit-price-icon operate-icon" data-specid="'+id+'" />  <img src="'+cdnUrl+'/assets/cashdesk/img/del_icon.svg" class="del-item-icon operate-icon" data-specid="'+id+'"/>';
            }

            if (cart_goods_html != '') {
                $(".cart-list").append(cart_goods_html);
                cart_goods_html = '';
            }
            $('#addGoodsModal').modal('hide');
        });
        //保存客户信息到session
        var serializedArray = JSON.stringify(goodsorders);
        sessionStorage.setItem('goodsorder_'+user_id, serializedArray);

        updateorderdetail();
        return false;
    });

    $(document).on("click", ".page-prev-btn", function () {
        var data_type = 'goods';
        var currentkey = sessionStorage.getItem('currentkey');
        if (currentkey) {
            var current_key = JSON.parse(currentkey);
            data_type = current_key['datatype'];
        }
        var cateid = $(".active").data('cateid');
        var searchword = $.trim($(".search-word").val());
        var page = $('.page-cur').text();
        page = page>1 ? page-1 :1;
        $('.page-cur').text(page);
        initdata(data_type,cateid,searchword,page);
    });

    $(document).on("click", ".page-next-btn", function () {
        var data_type = 'goods';
        var currentkey = sessionStorage.getItem('currentkey');
        if (currentkey) {
            var current_key = JSON.parse(currentkey);
            data_type = current_key['datatype'];
        }
        var cateid = $(".active").data('cateid');
        var searchword = $.trim($(".search-word").val());
        var page = $(this).data("page");
        initdata(data_type,cateid,searchword,page);
    });
    //初始化数据
    function initdata(datatype='goods',cateid=0,searchword='',page=1){
        //默认获取数据类型为goods
        if($.inArray(datatype, ['goods','services','cards']) == -1){
            layer.open({
                title:'提示信息',
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">数据类型错误，请确认后重试！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    layer.close(index);
                }
            });
            return false;
        }

        var currentid = cateid;

        var customerinfo =  sessionStorage.getItem('customer');
        var user_id = 0;
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            user_id = user_info.id;
        }

        if(user_id == 0 && cateid == 6){
            layer.open({
                title:'提示信息',
                type: 1, 
                area: ['280px', '180px'],
                content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">续卡前请先选择客户！</p>',
                btn: ['确定'], // 弹窗按钮
                btnAlign:"c",
                yes: function(index, layero){
                    layer.close(index);
                }
            });
            return false;
        }

        //加载数据
        $.ajax({
            type: 'post',
            url: 'cashdesk/index',
            data: {type: datatype,cateid: cateid,userid:user_id,searchword:searchword,page: page},
            dataType: 'json',
            success: function (ret) {
                var category_data = ret.data.category;
                var goods_data = ret.data.list.data;
                var current_page = ret.data.list.current_page;
                var per_page = ret.data.list.per_page;
                var last_page = ret.data.list.last_page;
                var category_list_html = '';
                var goods_list_html = '';
                
                if (ret.code == 1) {
                    if (category_data.length > 0) {
                        if(cateid == 0){
                            currentid = category_data[0].id;
                        }
                        for (var cate_key in category_data) {
                            if (category_data[cate_key].id == currentid) {
                                category_list_html += '<a class="list-group-item list-group-item-action active" data-cateid="'+category_data[cate_key].id+'" data-datatype="'+datatype+'">'+category_data[cate_key].name+'</a>';
                            }else{
                                category_list_html += '<a class="list-group-item list-group-item-action" data-cateid="'+category_data[cate_key].id+'" data-datatype="'+datatype+'">'+category_data[cate_key].name+'</a>';
                            }
                        }
                    }

                    if (goods_data.length > 0) {
                        for (var goods_key in goods_data) {
                            if(datatype == 'cards'){
                                goods_list_html += '<div class="col-md-5 cards-item cards-item-div" data-cateid="'+goods_data[goods_key].cateid+'" data-id="'+goods_data[goods_key].id+'" data-needupdate="0"  data-type="cards">';
                                goods_list_html += '<div class="row cards-item-info">';

                                if(goods_data[goods_key]['type'] != 4 ){
                                    if (goods_data[goods_key].vip_price == 0.00) {
                                        goods_list_html += '<div class="col-md-8" style="padding-left:0px;font-weight: bold;font-size: 15px;height:40px;"><span class="cards-item-info-name">'+goods_data[goods_key].name+'</span><span style="color:#fe234f;font-size:13px;">(耗卡:￥'+ parseFloat(goods_data[goods_key]['unit_price']).toFixed(2)+')</span></div>';
                                    }else{
                                        goods_list_html += '<div class="col-md-8" style="padding-left:0px;font-weight: bold;font-size: 15px;height:40px;"><span class="cards-item-info-name">'+goods_data[goods_key].name+'</span><span style="color:#fe234f;font-size:13px;">(耗卡:￥'+ parseFloat(goods_data[goods_key]['unit_price']).toFixed(2)+')</span>(vip:<span class="vip_price">'+goods_data[goods_key].vip_price+'</span>)</div>';
                                    }
                                }else{
                                    if (goods_data[goods_key].vip_price == 0.00) {
                                        goods_list_html += '<div class="col-md-8" style="padding-left:0px;font-weight: bold;font-size: 15px;height:40px;"><span class="cards-item-info-name">'+goods_data[goods_key].name+'</span></div>';
                                    }else{
                                        goods_list_html += '<div class="col-md-8" style="padding-left:0px;font-weight: bold;font-size: 15px;height:40px;"><span class="cards-item-info-name">'+goods_data[goods_key].name+'</span>(vip:<span class="vip_price">'+goods_data[goods_key].vip_price+'</span>)</div>';
                                    }
                                }

                                goods_list_html += '<div class="col-md-4" style="font-size: 20px;text-align:right;color:#fe234f;font-weight: bold;">￥<span class="cards-item-info-price">'+goods_data[goods_key].price+'</span></div></div>';
                                if(goods_data[goods_key]['type'] != 4 ){
                                    goods_list_html += '<div class="row" style="margin-left: 0px;margin-bottom: 15px;font-size: 14px;height:35px;">项目：<span class="cards-item-info-content">'+goods_data[goods_key].card_service+'</span></div>';
                                }else{
                                    goods_list_html += '<div class="row" style="margin-left: 0px;margin-bottom: 15px;font-size: 14px;height:35px;"></div>';
                                }
                                goods_list_html += '<div class="row cards-item-lifespan">';
                                goods_list_html += '<div class="col-md-8" style="padding-left:0px;font-size: 14px;">';
                                goods_list_html += '有效期: <span class="cards-item-lifespan-expiration">'+goods_data[goods_key].time+'</span></div>';
                                goods_list_html += '<div class="col-md-4" style="text-align:right;font-weight: bold;font-size: 16px;">';
                                if(goods_data[goods_key]['type'] != 4 ){
                                    goods_list_html += '<span class="cards-item-lifespan-times">'+goods_data[goods_key].total+'</span> 次</div></div>';
                                }else{
                                    goods_list_html += '<span class="cards-item-lifespan-times"></span></div></div>';
                                }
                                
                                goods_list_html += '<div class="row cards-item-detail"><div class="col-sm-4"><span class="cards-item-detail-title">'+goods_data[goods_key].type_name+'</span></div><div class="col-sm-8" style="text-align:right;padding-right: 2%;">';
                                goods_list_html += '<input type="button" class="reduce-action" value="-" onclick="modityCardsNum($(this))"/>';
                                goods_list_html += '<input type="number" min="0" step="1" class="buy-quantity" value="0" data-type="cards"/>';
                                goods_list_html += '<input type="button" class="incr-action" value="+" onclick="modityCardsNum($(this),\'incr\')"/>';
                                goods_list_html += '</div></div></div>';
                            }else{
                                goods_list_html += '<div class="goods-list-item goods-list-item-action" data-id="'+goods_data[goods_key].id+'"  data-type="'+datatype+'" data-url="cashdesk/goods/getgoodsskus">';
                                goods_list_html += '<img class="goods-img img-review" src="'+goods_data[goods_key].image+'" alt="">';
                                goods_list_html += '<div class="goods-info">';
                                goods_list_html += '<div>'+goods_data[goods_key].title+'</div>';
                                if (goods_data[goods_key].vip_price != 0.00) {
                                    goods_list_html += '<div style="margin-top: 6px;color: red">'+goods_data[goods_key].price+'(vip:'+goods_data[goods_key].vip_price+')</div>';
                                }else{
                                    goods_list_html += '<div style="margin-top: 6px;color: red">'+goods_data[goods_key].price+'</div>';
                                }
                                
                                goods_list_html += '</div>';
                                goods_list_html += '</div>';
                            }
                        }
                    }
                    //分类html
                    $('.list-group').html(category_list_html);
                    //商品html
                    $('.goods-list-content').html(goods_list_html);
                    $('.page-cur').text(current_page);
                    $('.page-total').text(last_page);
                    $(".page-prev-btn").attr("data-page",1);
                    $(".page-next-btn").attr("data-page",last_page);

                    if (current_page > 1) {
                       $(".page-prev-btn").attr("data-page",current_page-1); 
                    }

                    if (current_page < last_page) {
                       $(".page-next-btn").data("page",current_page+1); 
                    }
                }
                return false;
            }
        });
        
        // $(".page-content").hide();
        //默认加载买家信息
        var customerinfo =  sessionStorage.getItem('customer');
        var user_id = 0;
        if(customerinfo && customerinfo.length != 0){
            var user_info = JSON.parse(customerinfo);
            user_id = user_info.id;
            var show_user_info_html = '<div class="col-md-2">';
                show_user_info_html += '<img class="goods-img img-review" src="'+user_info.avatar+'" alt=""></div>';
                show_user_info_html += '<div class="col-md-6">';
                show_user_info_html += '<div class="row"><label>'+user_info.nickname+'  '+user_info.groupname+'</label></div>';
                show_user_info_html += '<div class="row"><label>'+user_info.mobile+'</label></div></div>';
                show_user_info_html += '<div class="col-md-4 re-choose-user">重新选择</div>';
            $('.label-choose-user').addClass('label-choosed-user').html(show_user_info_html);
        }else{
            var show_user_info_html = '<label class="label label-btns label-choose-btn">+</label>';
                show_user_info_html += '<label class="label label-btns label-choose-title">点击选择客户</label>';
            $('.label-choosed-user').addClass('label-choose-user').removeClass('label-choosed-user').html(show_user_info_html); 
        }

        //默认加载商品购物车信息
        $(".cart-list").html("");
        var cart_goods_html = '';
        if(user_id != 0){
            var orderkey = 'goodsorder_'+user_id;
            if (datatype == "cards") {
                orderkey = 'cardsorder_'+user_id;
            }

            var ordersList = sessionStorage.getItem(orderkey);
            if(ordersList){
                var orders_list = JSON.parse(ordersList);
                if (datatype == "cards") {
                    for (var card_keys in orders_list) {
                        var card_cart = orders_list[card_keys];
                        cart_goods_html += '<div class="col-md-5 cards-item cards-item-div" data-cateid="'+card_cart['cateid']+'" data-id="'+card_cart['spec_id']+'" data-needupdate="1"  data-type="cards" style="width:100%;">';
                        cart_goods_html += '<div class="row cards-item-info">';
                        cart_goods_html += '<div class="col-md-8" style="padding-left:0px;font-weight: bold;font-size: 18px;"><span class="cards-item-info-name">'+card_cart['spec_name']+'</span></div>';
                        cart_goods_html += '<div class="col-md-4" style="font-size: 20px;text-align:right;color:#fe234f;font-weight: bold;">￥<span class="cards-item-info-price">'+card_cart['old_spec_price']+'</span></div></div>';
                        if (card_cart['spec_service'] == '') {
                            cart_goods_html += '<div class="row" style="margin-left: 0px;margin-bottom: 15px;font-size: 14px;"></div>';
                        }else{
                            cart_goods_html += '<div class="row" style="margin-left: 0px;margin-bottom: 15px;font-size: 14px;">项目：<span class="cards-item-info-content">'+card_cart['spec_service']+'</span></div>';
                        }
                        cart_goods_html += '<div class="row cards-item-lifespan">';
                        cart_goods_html += '<div class="col-md-8" style="padding-left:0px;font-size: 14px;">有效期: <span class="cards-item-lifespan-expiration">'+card_cart['spec_expiration']+'</span></div>';
                        
                        cart_goods_html += '<div class="col-md-4" style="text-align:right;font-weight: bold;font-size: 16px;">';
                        if (card_cart['spec_total'] != '') {
                            cart_goods_html += '<span class="cards-item-lifespan-times">'+card_cart['spec_total']+'</span> 次</div></div>';
                        }else{
                            cart_goods_html += '<span class="cards-item-lifespan-times"></span></div></div>';
                        }
                        
                        cart_goods_html += '<div class="row cards-item-detail"><div class="col-sm-4"><span class="cards-item-detail-title">'+card_cart['spec_type']+'</span></div>';
                        if (card_cart['cateid'] == 6) {
                            cart_goods_html += '<div class="col-sm-8" style="width: auto;text-align:center;padding-left: 0;font-size: 14px;">';
                            cart_goods_html += '<div class="col-md-8" style="width: auto;text-align: center;padding-left:0px;font-size: 14px;">充值金额<span class="cards-item-lifespan-expiration"><input type="number" min="0" step="0.01" class="add_amount form-control" value="'+card_cart['spec_price']+'" style="text-align:center;width:80px;"/></span></div>';
                            cart_goods_html += '<div class="col-md-8" style="width: auto;text-align: center;padding-left:0px;font-size: 14px;">赠送金额<span class="cards-item-lifespan-expiration"><input type="number" min="0" step="0.01" class="gift_amount form-control" value="'+card_cart['gift_price']+'" style="text-align:center;width:80px;"/></span></div>';
                        }else{
                            cart_goods_html += '<div class="col-sm-8" style="text-align:right;padding-right: 2%;">';
                            cart_goods_html += '<input type="button" class="reduce-action" value="-" onclick="modityCardsNum($(this))"/>';
                            cart_goods_html += '<input type="number" min="0" step="1" class="buy-quantity" value="'+card_cart['spec_number']+'" data-type="cards"/>';
                            cart_goods_html += '<input type="button" class="incr-action" value="+" onclick="modityCardsNum($(this),\'incr\')"/>';
                        }
                        cart_goods_html += '</div></div>';
                        cart_goods_html += '<div class="hover-card-operate-div"><img src="'+cdnUrl+'/assets/cashdesk/img/del_icon.svg" class="del-card-icon operate-icon" data-specid="'+card_cart['spec_id']+'"/></div>';
                        cart_goods_html += '<p class="card-text card-service">';
                        if (card_cart['staff_ids']) {
                            cart_goods_html += '<span class="card-attendant" style="line-height: 30px;color:#ff0000;" data-specid="'+card_cart['spec_id']+'" data-serveid="'+card_cart['staff_id']+'">';
    
                            cart_goods_html += '<span style="margin-left: 10px;">'+card_cart['staff_name']+'<img src="'+cdnUrl+'/assets/cashdesk/img/right-icon.svg" class="right-icon" /> </span></span>';
                        }else{
                            cart_goods_html += '<span class="card-attendant" style="line-height: 30px;color:#ff0000;" data-specid="'+card_cart['spec_id']+'" data-serveid="0">选择 销售人员 </span>';
                        }

                        cart_goods_html += '</p></div>';
                    }
                }else{
                    for (var goods_keys in orders_list) {
                        var goods_cart = orders_list[goods_keys];
                        cart_goods_html += '<div class="card border card-item card-item-service" data-specid="'+goods_cart['spec_id']+'">';
                        cart_goods_html += '<div class="row card-item-row"><div class="col-md-2">';
                        cart_goods_html += '<img src="'+goods_cart['goods_img']+'" class="card-img-top img-review goods-img" alt=""></div><div class="col-md-10">';
                        cart_goods_html += '<div class="card-body trdata" data-goodsid="'+goods_cart['goods_id']+'" data-id="'+goods_cart['spec_id']+'" data-stock="'+goods_cart['spec_stock']+'" data-price="'+goods_cart['spec_price']+'">';
                        cart_goods_html += '<h5 class="card-title">'+goods_cart['goods_name']+'</h5>';
                        if (goods_cart['datatype'] == 'services') {
                            cart_goods_html += '<p class="card-text-price">￥ '+goods_cart['spec_price']+'<span style="color:#000"> (耗卡:￥'+ parseFloat(goods_cart['uprice']).toFixed(2)+')</span></p>';
                        }else{
                            cart_goods_html += '<p class="card-text-price">￥ '+goods_cart['spec_price']+'</p>';
                        }
                        cart_goods_html += '<p class="card-text">规格：'+goods_cart['spec_name']+'<span class="card-operate"><input type="button" class="reduce-action available-action" value="-" onclick="modityGoodsNum($(this),\'reduce\',1)" style="width: 20px;height: 20px;font-size: 13px;" /><input type="number" max="'+goods_cart['spec_stock']+'" min="0" step="1" class="buy-quantity" value="'+goods_cart['spec_number']+'" style="font-size:13px;" data-type="goods" /><input type="button" class="incr-action available-action" value="+" onclick="modityGoodsNum($(this),\'incr\',1)" style="width: 20px;height: 20px;font-size: 13px;" /></span></p>';
                        cart_goods_html += '<p class="card-text card-text-service">';
                        if (goods_cart['staff_ids']) {
                            cart_goods_html += '<span class="card-attendant" style="line-height: 30px;color:#ff0000;" data-specid="'+goods_cart['spec_id']+'" data-serveid="'+goods_cart['staff_id']+'">';
                            // cart_goods_html += '<img class="img card-text-service-img img-review" src="'+cdnUrl+goods_cart['staff_img']+'" alt="" >';
                            cart_goods_html += '<span style="margin-left: 10px;">'+goods_cart['staff_name']+'<img src="'+cdnUrl+'/assets/cashdesk/img/right-icon.svg" class="right-icon" /> </span></span>';
                        }else{
                            if (goods_cart['datatype'] == 'services') {
                                cart_goods_html += '<span class="card-attendant" style="line-height: 30px;color:#ff0000;" data-specid="'+goods_cart['spec_id']+'" data-serveid="0">选择 销售人员/解痛师 </span>';
                            }else{
                                cart_goods_html += '<span class="card-attendant" style="line-height: 30px;color:#ff0000;" data-specid="'+goods_cart['spec_id']+'" data-serveid="0">选择 销售人员 </span>';
                            }
                        }
      
                        if (goods_cart['datatype'] == 'services') {
                            if(goods_cart['cards'] && Object.getOwnPropertyNames(goods_cart['cards']).length > 0){
                                cart_goods_html += '<span class="card-equitycard card-equitycard-operate" data-specid="'+goods_cart['spec_id']+'">已选次卡</span></p>';
                            }else{
                                cart_goods_html += '<span class="card-equitycard card-equitycard-operate" data-specid="'+goods_cart['spec_id']+'">选择次卡</span></p>';
                            }
                        }
                        cart_goods_html += '</p></div></div><div class="hover-operate-div">';
                        cart_goods_html += '<img src="'+cdnUrl+'/assets/cashdesk/img/edit_icon.svg" class="edit-price-icon operate-icon" data-originalprice="'+goods_cart['spec_originalprice']+'" data-price="'+goods_cart['spec_price']+'" data-specid="'+goods_cart['spec_id']+'" />  <img src="'+cdnUrl+'/assets/cashdesk/img/del_icon.svg" class="del-item-icon operate-icon"  data-specid="'+goods_cart['spec_id']+'"/>';
                        cart_goods_html += '</div></div></div>';
                    }
                }
            }
        }
        
        if (cart_goods_html != '') {
            $(".cart-list").html(cart_goods_html);
            cart_goods_html = '';
        }

        var currentkey = {"datatype":datatype};
        var serializedArray = JSON.stringify(currentkey);
        sessionStorage.setItem("currentkey", serializedArray);

        updateorderdetail(datatype);
    }

    //更新订单商品数量金额
    function updateorderdetail(datatype="goods",need_up=0) {
        //获取用户信息
        var customerinfo =  sessionStorage.getItem('customer');
        var user_id = 0;
        var totalorderfee = 0;
        var objkey = 'goodsorder';
        if (datatype == "cards") {
            objkey = 'cardsorder';
        }
        var ordersList = {};
        if(customerinfo && customerinfo.length != 0){
            //用户信息
            var user_info = JSON.parse(customerinfo);
            //等级折扣
            var countkey = objkey+"count_"+user_info.id;
            var orderkey = objkey+"_"+user_info.id;
            ordersList = sessionStorage.getItem(orderkey);
            if(ordersList){
                var orders = JSON.parse(ordersList);
                var originalfee = 0;
                var originalfee = 0;
                var discountfee = 0;
                var upricefee = 0;
                for (var goods_keys in orders) {
                    var spec_originalprice = parseFloat(orders[goods_keys]['spec_originalprice']).toFixed(2);
                    var price = parseFloat(orders[goods_keys]['spec_price']).toFixed(2);
                    var number = parseInt(orders[goods_keys]['spec_number']);
                    totalorderfee += parseFloat(price).toFixed(2) * number;
                    originalfee += parseFloat(spec_originalprice).toFixed(2) * number;
                    discountfee = parseFloat(discountfee) + parseFloat(orders[goods_keys]['spec_discountfee']);
                    upricefee += parseFloat(orders[goods_keys]['uprice']);
                }
                var orderAmount = {};//订单金额统计列表
                //订单金额统计列表
                var orderCount =  sessionStorage.getItem(countkey);
                if(orderCount){
                    orderAmount = JSON.parse(orderCount);
                }else{
                    orderAmount = default_count;
                }
                orderAmount['totalfee'] = parseFloat(totalorderfee).toFixed(2);
                orderAmount['originalfee'] = parseFloat(originalfee).toFixed(2);
                orderAmount['modifyfee'] = parseFloat(totalorderfee).toFixed(2);
                orderAmount['upricefee'] = parseFloat(upricefee).toFixed(2);
                if (user_info.level > 1) {
                    orderAmount['vipdiscount'] = 0;
                }else{
                    if (user_info.level_discount == 0 || user_info.level_discount == 1) {
                        orderAmount['vipdiscount'] = 0;
                    }else{
                        orderAmount['vipdiscount'] = orderAmount['totalfee'] * (1 - parseFloat(user_info.level_discount).toFixed(2));
                    }
                }
                

                $(".ordertotalfee").text('￥'+parseFloat(totalorderfee).toFixed(2));
                if (orderAmount['modifyfee']) {
                    $(".ordertotalfee").text('￥'+parseFloat(orderAmount['modifyfee']).toFixed(2));
                }else{
                    $(".ordertotalfee").text('￥'+parseFloat(totalorderfee).toFixed(2));
                }
                
                orderAmount['discountfee'] = parseFloat(discountfee).toFixed(2);

                $(".orderdiscountfee").text('￥0');

                //更新用户信息
                var serializedArray = JSON.stringify(orderAmount);
                sessionStorage.setItem(countkey, serializedArray);
            }
        }

        if(!ordersList){
            $(".btn-operate-order").attr('disabled',true);
        }else{
            $(".btn-operate-order").attr('disabled',false);
        }
        
        var search_orders = getItemsByKeyword(objkey+'_');
        $(".notification-count").text(search_orders.length);
    }

    //生成订单号
    function createOrderNo(){
        let now = new Date();
        let year = now.getFullYear();
        let month = String(now.getMonth() + 1).padStart(2, '0');
        let day = String(now.getDate()).padStart(2, '0');
        let hours = String(now.getHours()).padStart(2, '0'); 
        let minutes = String(now.getMinutes()).padStart(2, '0');
        let seconds = String(now.getSeconds()).padStart(2, '0');
        let milliseconds = String(now.getMilliseconds()).padStart(3, '0');
        return  `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`+getRandomInt(111111, 999999); 
    }

    // 生成1000到9999之间的随机整数
    function getRandomInt(min, max) {
        // min - 最小值（包含）
        // max - 最大值（包含）
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function getItemsByKeyword(keyword) {
        var results = [];
        for (let i = 0; i < sessionStorage.length; i++) {
            let key = sessionStorage.key(i);
            if (key.includes(keyword)) {
                results.push({ key, value: sessionStorage.getItem(key) });
            }
        }
        return results;
    }

    //改价后更新卡项优惠金额
    function updateDiscountFee(userid){
        var orderkey = 'goodsorder_'+userid;
        var orderlist = sessionStorage.getItem(orderkey);
        if (orderlist) {
            var orders = JSON.parse(orderlist);
            for(var x in orders){
                if (orders[x]['cards']) {
                    var cards_list = orders[x]['cards'];
                    if (cards_list) {
                        var cardused = {};
                        var totalcount = 0;
                        var spec_price = orders[x]['spec_price'];
                        for(var i in cards_list){
                            totalcount += cards_list[i];
                        }
                        orders[x]['spec_discountfee'] = parseFloat(totalcount * spec_price).toFixed(2);
                        var serializedArray = JSON.stringify(orders);
                        sessionStorage.setItem(orderkey, serializedArray);
                    }
                }
            }
            
        }
    }

    function mergeAndDeduplicate(arr1, arr2, keys) {
        if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
            throw new Error('Both arr1 and arr2 must be arrays');
        }
        const combined = [...arr1, ...arr2];
        const uniqueMap = new Map();

        combined.forEach(item => {
            const key = keys.map(k => item[k]).join('-');
            uniqueMap.set(key, item);
        });

        return Array.from(uniqueMap.values());
    }


    // 初始化弹窗相关事件
    // 打开弹窗
    // 确保 Layui 库已加载
    // 确保 Layui 库已加载
    layui.use(['layer', 'laypage', 'jquery'], function () {
        var layer = layui.layer;
        var laypage = layui.laypage;
        var $ = layui.jquery;

        $('.label-btn-addgift').click(function () {
            var customerinfo = sessionStorage.getItem('customer');
            if(!customerinfo || customerinfo.length == 0){
                layer.open({
                    title:'提示信息',
                    type: 1, 
                    area: ['280px', '180px'],
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">客户不存在，请先选择客户！</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        layer.close(index);
                    }
                });
                return false;
            };

            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;
            var currentkey = sessionStorage.getItem('currentkey');
            if (currentkey) {
                var current_key = JSON.parse(currentkey);
                data_type = current_key['datatype'];
            }

            var ordercount = sessionStorage.getItem('goodsordercount_'+user_id);
            if (data_type == "cards") {
                ordercount = sessionStorage.getItem('cardsordercount_'+user_id);
            }

            if(!ordercount || ordercount.length == 0){
                layer.open({
                    title:'提示信息',
                    type: 1, 
                    area: ['280px', '180px'],
                    content: '<p style="padding: 10px;font-size: 16px;color: #ff0000;">购物车没有商品，请先去选择商品！</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        layer.close(index);
                    }
                });
                return false;
            }
            // 初始化服务列表
            initcategory();
            loadlist();
            $('#addGiveModal').modal('show');
        });

        // 添加 tab 点击事件监听
        $('.nav-item').on('click', function (e) {
            e.preventDefault();
            var datatype = $(this).data('type');
            var category = 0;
            var keyword = '';
            $('#service-category').val(0);
            $('#service-search').val('');
            initcategory(datatype);
            loadlist(category, keyword, datatype, 1);
        });

        // 服务搜索按钮点击事件
        $('#gift-search-btn').click(function () {
            var category = $('#service-category').val();
            var keyword = $('#service-search').val();
            var datatype = $('.nav-item.active')? $('.nav-item.active').data('type') : 1;
            loadlist(category, keyword, datatype, 1);
        });

        // 全选服务复选框事件
        $('#select-all-service').click(function () {
            var isChecked = $(this).is(':checked');
            $('#service-list input[type="checkbox"]').prop('checked', isChecked);
        });

        // 确认按钮点击事件
        $('#confirm-add-give').click(function () {
            //获取用户信息和订单类型
            var customerinfo = sessionStorage.getItem('customer');
            if(!customerinfo || customerinfo.length == 0){
                layer.open({
                    title:'提示信息',
                    type: 1, 
                    area: ['280px', '180px'],
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">客户不存在，请先选择客户！</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        layer.close(index);
                    }
                });
                return false;
            };

            var user_info = JSON.parse(customerinfo);
            var user_id = user_info.id;
            var currentkey = sessionStorage.getItem('currentkey');
            if (currentkey) {
                var current_key = JSON.parse(currentkey);
                data_type = current_key['datatype'];
            }

            var countkey = 'goodsordercount_'+user_id;
            
            if (data_type == "cards") {
                countkey = 'cardsordercount_'+user_id
            }
            var ordercount = sessionStorage.getItem(countkey);

            if(!ordercount || ordercount.length == 0){
                layer.open({
                    title:'提示信息',
                    type: 1, 
                    area: ['280px', '180px'],
                    content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;text-align:center;">购物车没有商品，请先去选择商品！</p>',
                    btn: ['确定'], // 弹窗按钮
                    btnAlign:"c",
                    yes: function(index, layero){
                        layer.close(index);
                    }
                });
                return false;
            }

            var item = [];
            var type = $('.nav-item.active').data('type');
            $('#service-list input[type="checkbox"]:checked').each(function () {
                var itemid = $(this).val();
                var number = $(this).parents('tr').find('.gift_number').val();
                var goods_name = $(this).parents('tr').find('.goods_name').text();
                var price = $(this).parents('tr').find('.price').text();
                item.push({itemid:itemid,number:number,type:type,goods_name:goods_name,price:price});
            });

            var ordersCount = JSON.parse(ordercount);



            var giftdata = [];
            if (ordersCount.giftdata != undefined) {
                giftdata = ordersCount.giftdata;
            }

            ordersCount.giftdata = mergeAndDeduplicate(giftdata,item,['itemid','type'])

             //保存赠送到session
            var serializedArray = JSON.stringify(ordersCount);
            sessionStorage.setItem(countkey, serializedArray);

            $('#addGiveModal').modal('hide');
        });

        //清除已选赠送
        $('#clear-gift-btn').click(function () {
            layer.confirm('是否确定清除已选赠品项目？', {
                title: "操作提示",
                btn: ['确定', '我再想想'], //可以无限个按钮
                yes:function(index, layero){
                    //获取用户信息和订单类型
                    var customerinfo = sessionStorage.getItem('customer');
                    if(customerinfo && customerinfo.length != 0){
                        var user_info = JSON.parse(customerinfo);
                        var user_id = user_info.id;
                        var currentkey = sessionStorage.getItem('currentkey');
                        if (currentkey) {
                            var current_key = JSON.parse(currentkey);
                            data_type = current_key['datatype'];
                        }
                        var countkey = 'goodsordercount_'+user_id;
                        
                        if (data_type == "cards") {
                            countkey = 'cardsordercount_'+user_id
                        }
                        var ordercount = sessionStorage.getItem(countkey);

                        if(ordercount && ordercount.length != 0){
                            var ordercounts = JSON.parse(ordercount);
                            if (ordercounts.giftdata) {
                                ordercounts.giftdata = []
                                var serializedArray = JSON.stringify(ordercounts);
                                sessionStorage.setItem(countkey, serializedArray);
                            }
                        }
                    };
                    layer.close(index);
                }
             });
        });
        
        // 初始化服务列表
        function initcategory(type = 1) {
            $.ajax({
                type: 'POST',
                url: 'cashdesk/index/getcategory',
                dataType: "json",
                data: {
                    type: type
                },
                success: function (ret) {
                    if (ret.code == 1) {
                        var retdata = ret.data;
                        if (retdata.length > 0) {
                            var category_list_html = '<option value="0">所有分类</option>';
                            $.each(retdata, function (index, item) {
                                category_list_html += '<option value="' + item.id + '">' + item.name + '</option>';
                            });
                            $("#service-category").html('');
                            $("#service-category").append(category_list_html);
                        }
                    }
                }
            });
            return false;
        }

        // 加载服务列表
        function loadlist(category, keyword, datatype = 1, page = 1) {
            $.get('cashdesk/index/getDataList', { type: datatype, cateid: category, searchword: keyword, page: page }, function (res) {
                $('#service-list').html('');
                if (res.code == 1) {
                    // 清空原有列表内容
                    var dataList = res.data.data;
                    dataList.forEach(function (item, index) {
                        var row = `
                            <tr>
                                <td><input type="checkbox" class="item" value="${item.id}"></td>
                                <td><span class="goods_name">${item.title}</span><br/>分类: ${item.cate_name}</td>
                                <td class="price">${item.price}</td>
                                <td ><input type="number" min="1" class="gift_number form-control" value="1" style="text-align:center;width:80px;"/></td>
                                <td>${item.createtime}</td>
                            </tr>
                        `;
                        $('#service-list').append(row);
                    });
                    // 初始化分页
                    initPagination(res.data.total, category, keyword, datatype, page);
                    $('#service-list tr').on('click', function (e) {
                        // 防止点击 checkbox 时触发两次事件
                        if (e.target.type!== 'checkbox') {
                            var checkbox = $(this).find('input[type="checkbox"]');
                            checkbox.prop('checked',!checkbox.prop('checked'));
                        }
                    });
                } else {
                    Fast.api.toastr.error(res.msg);
                }
            }, 'json');
        }

        // 初始化分页
        function initPagination(total, category, keyword, datatype, currentPage) {
            laypage.render({
                elem: 'service-pagination',
                count: total,
                limit: 6,
                curr: currentPage, // 设置当前页码
                layout: ['prev', 'page', 'next', 'count'],
                jump: function (obj, first) {
                    if (!first) {
                        loadlist(category, keyword, datatype, obj.curr);
                    }
                }
            });
        }
    });
});
